﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace MyLib
{
    /// <summary>
    /// RoomActor 的FPS组件 
    /// 执行在 Room线程
    /// </summary>
    public class FPSRoom
    {
        public enum State
        {
            Idle,
            Connecting,
            Connected,
            Closed,
        }
        public State state = State.Idle;
        private FPSServerInfo serverInfo;
        /// <summary>
        /// 是否启动FPS服务器功能
        /// </summary>
        public bool inUse = true;

        private RoomActor room;
        private ActorSynchronizationContext mainLoop;
        public FPSRoom(RoomActor r)
        {
            room = r;
            mainLoop = room._messageQueue;
        }

        /// <summary>
        /// 发送FPS服务器的状态 给所有客户端
        /// 
        /// 客户端实体属性订阅
        /// 实体属性版本 Version 信息 Frame信息
        /// 服务器下发Delta实体属性信息
        /// Proto, Id, 实体类型 协议实体ID
        /// Attri 属性
        /// </summary>
        public void SyncRoomInfo()
        {
            if (!inUse) return;

            var gc = MMFPSRoomInfo.CreateBuilder();
            gc.Cmd = "InitFPSRoomInfo";
            gc.Ip = serverInfo.localInfo.localIp;
            gc.Port = serverInfo.localInfo.localPort;
            gc.State = (int)state;
            LogHelper.Log2("SyncRoomInfo:"+gc);
            room.playerCom.BroadcastToAll(gc);
        }

        /// <summary>
        /// 发送玩家数据给FPSServer
        /// 
        /// RoomActor 负责调用这里
        /// 发送选择的玩家信息给FPS游戏服务器 每个玩家选择的FPS角色信息 通知给FPSServer
        /// </summary>
        public async Task SendPlayerInfoToFpsServer()
        {
            LogHelper.Log2("SendPlayerInfoToFpsServer:"+serverInfo.fpsRoomInfo);
            if (!inUse) return;
            var gc = MMFPSRoomInfo.CreateBuilder();
            var pl = room.playerCom.players;
            foreach(var p in pl)
            {
                gc.AddAvatarInfos(p.GetAvatarInfo());
            }
            gc.Cmd = "EnterFPSRoom";

            //通知FPS服务器准备开始Room房间等待玩家加入
            await serverInfo.fpsConnect.SendWaitResponse(gc);
            //接着通知各个客户端尝试连接进入FPS服务器
        }
        /// <summary>
        /// 启动Unity实例
        /// </summary>
        public async Task StartRoomGame()
        {
            if (!inUse) return;

            state = State.Connecting;
            //启动新进程跑Unity服务器
            try
            {
                var process = new Process();
                var startInfo = new ProcessStartInfo();

                if (Util.GetPlatform() == OSPlatform.Windows)
                {
                    startInfo.WorkingDirectory = "test";
                    startInfo.FileName = "fps.exe";
                    startInfo.WindowStyle = ProcessWindowStyle.Normal;
                    startInfo.Arguments = "-batchmode";
                    startInfo.RedirectStandardOutput = true;
                    startInfo.RedirectStandardError = true;
                    process.StartInfo = startInfo;
                    process.EnableRaisingEvents = true;

                    var ret = process.Start();
                    LogHelper.Log2("StartGameServer:" + ret);
                }
            }catch(Exception exp)
            {
                LogHelper.LogError2("StartFPSServerError:"+exp.ToString());
            }
            var fps = ActorManager.Instance.GetActor<FPSServerMgr>();
            var gameServer = await fps.GetServer();
            await gameServer.SetUsedRoom(this);
            serverInfo = gameServer;
            state = State.Connected;
        }

        /// <summary>
        /// 需要和Room同线程处理
        /// TODO:处理关闭FPSRoom功能
        /// </summary>
        /// <returns></returns>
        internal async Task OnClose()
        {
            await mainLoop;

        }
    }
}
